(function() {

    jQuery(document).ready(function(){

        var SELECTORS = {
            QUICK_SEARCH: "#btnQuickSearch",
            QUICK_SEARCH_INPUT: "#quickSearch",
            ADVANCE_SEARCH: "#advSearchSubmit",
            ADVANCE_SEARCH_ICON: "#btnAdvSearch",
            ADVANCE_SEARCH_PANEL: "#advSearchPanel",
            TABLE: "#supplier-table",
            CREATE_BUTTON: "#create-supplier",
            CREATE_MODAL: "#create-supplier-form",
            EDIT_MODAL: "#edit-supplier-form"
        };

        var conditions = {},
            tableData = {},
            supplierCreationModal = $(SELECTORS.CREATE_MODAL),
            supplierEditionModal = $(SELECTORS.EDIT_MODAL);

        var dataTable = $(SELECTORS.TABLE).DataTable({
            "processing": true,
            "serverSide": true,
            "lengthMenu": [[10, 25, 50], [10, 25, 50]],
            "dom": '<"bottom"rtflp>',
            "searching": false,
            "pagingType": "full_numbers",
            "deferRender": true,
            "ajax": {
                "traditional": true,
                "url": "/suppliers/client_search.action",
                "dataFilter": function(data) {
                    var json = jQuery.parseJSON(data);
                    tableData = json.data.reduce(function(a, b) {
                        a[b.id] = b;
                        return a;
                    }, {});
                    json.recordsTotal = json.total;
                    json.recordsFiltered = json.total;
                    return JSON.stringify(json);
                },
                "data": function (data) {
                    var sort = [];
                    for (var i = 0; i < data.order.length; i++) {
                        var order = data.order[i],
                            column = data.columns[order.column];
                        sort.push((column.name || column.data) + "," + order.dir);
                    }

                    return $.extend({
                        page: Math.floor(data.start / data.length + 1),
                        size: data.length,
                        sort: sort
                    }, conditions);
                }
            },
            "tableTools": {
                "sRowSelect": "bootstrap"
            },
            "columns": [
                { "data": "code", "name": "supp_code" },
                { "data": "name", "name": "supp_name" },
                { "data": "remark" },
                { "mRender": function(data, type, row) {
                    return '<button data-id="' + row.id + '" type="button" class="btn btn-info btn-xs btn-supplier-edit"><i class="fa fa fa-edit"></i>修改</button> \
                            <button data-id="' + row.id + '" type="button" class="btn btn-danger btn-xs btn-supplier-delete"><i class="fa fa-trash-o"></i>删除</button>'
                }}
            ],
            "columnDefs": [
                { "orderable":true, "targets":[0] },
                { "orderable":true, "targets":[1] },
                { "orderable":true, className:"truncate-text supplier-column-detail", "targets":[2] },
                { "orderable":false, "targets":[3] }
            ],
            "order": [[ 0, "desc" ]]
        });

        // 注册编辑事件
        $(SELECTORS.TABLE).on("click", ".btn-supplier-edit", function() {
            var id = $(this).data("id"), data = tableData[id];
            supplierEditionModal.data("id", id);
            supplierEditionModal.find("form")
                .field("supplierCode", data.code)
                .field("supplierName", data.name)
                .field("enterprise", data.enterpriseId)
                .field("supplierRemark", data.remark);
            window.top.window.borrowCustomModalDialog(supplierEditionModal)
                .modal("show")
                .one("hidden.bs.modal", function() {
                    window.top.window.returnCustomModalDialog();
                    supplierEditionModal.find("form").validate().clear();
                });
        });

        // 注册删除事件
        $(SELECTORS.TABLE).on("click", ".btn-supplier-delete", function() {
            var id = $(this).data("id"), data = tableData[id];
            window.top.window.showModalConfirm("确定要删除店铺供货商吗？", function() {
            	var loading = window.top.window.getIndexBusyOverlay();
                $.ajax({
                    method: "DELETE",
                    url: "/suppliers/" + id + ".action?enterprise=" + data.enterpriseId,
                    beforeSend:function(){
                        if(loading) {
                        	loading.settext("正在处理中，请稍后...");
                        }
                    }
                }).done(function() {
                	loading.remove();
                    dataTable.draw();
                    window.top.window.showScoMessage('ok', '删除成功');
                }).fail(function(resp) {
                	loading.remove();
                    window.top.window.showModalAlert(resp.responseJSON.errorMessage);
                });
            });
        });

        // 提示信息Tooltip
        $(SELECTORS.TABLE).tooltip({
            selector: ".supplier-column-detail",
            container: "body",
            title: function() {
                if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                    return $(this).text();
                }
            }
        });

        //低级查询按钮
        $(SELECTORS.QUICK_SEARCH).click(function () {
            conditions = {
                keyword: encodeURI($(SELECTORS.QUICK_SEARCH_INPUT).val())
            };
            dataTable.draw();
        });

        //高级查询按钮
        $(SELECTORS.ADVANCE_SEARCH).click(function () {
            conditions = {
                conditions: encodeURI(JSON.stringify($("#frmAdvSearch").formJson()[0]))
            };
            dataTable.draw();
            hideAdvanceSearchPanel();
        });

        //高级查询隐藏
        $(SELECTORS.ADVANCE_SEARCH_ICON).click(function (event) {
            $(SELECTORS.ADVANCE_SEARCH_PANEL).toggle();
            $(SELECTORS.QUICK_SEARCH).toggle();
            $(this).children("i:eq(0)").toggleClass("fa-angle-double-down fa-angle-double-up");
            event.stopPropagation();
        });

        $("body").click(function(event){
            if (!$(event.target).parents(SELECTORS.ADVANCE_SEARCH_PANEL).length) {
                hideAdvanceSearchPanel();
            }
        });

        // 搜索框的回车事件
        $(SELECTORS.QUICK_SEARCH_INPUT).keydown(function(e){
            if(e.keyCode==13 && $(SELECTORS.QUICK_SEARCH).is(":visible")){
                $(SELECTORS.QUICK_SEARCH).click();
            }
        });

        // 添加供应商
        $(SELECTORS.CREATE_BUTTON).click(function() {
            window.top.window.borrowCustomModalDialog(supplierCreationModal)
                .modal("show")
                .one("hidden.bs.modal", function() {
                    window.top.window.returnCustomModalDialog();
                    supplierCreationModal.find("form").validate().clear();
                });
        });

        // 创建表单 - 初始化表单验证器
        supplierCreationModal.find("form").validate({
            ignore: "",
            errorPlacement: function(error, element)
            {
                error.insertAfter(element);
            },
            submitHandler: function(form) {
            	var loading = window.top.window.getIndexBusyOverlay();
                var json = formJson(form);
                $.ajax({
                    method: "POST",
                    contentType: "application/json; charset=UTF-8",
                    dataType: "json",
                    url: "/suppliers.action",
                    data: JSON.stringify({
                        code: json.supplierCode,
                        name: json.supplierName,
                        enterpriseId: json.enterprise,
                        remark: json.supplierRemark
                    }),beforeSend:function(){
                        if(loading) {
                        	loading.settext("正在处理中，请稍后...");
                        }
                    }
                }).done(function() {
                	loading.remove();
                    supplierCreationModal.modal("hide");
                    dataTable.draw();
                    window.top.window.showScoMessage('ok', '添加成功');
                }).fail(function(resp) {
                	loading.remove();
                    window.top.window.showModalAlert(resp.responseJSON.errorMessage);
                });
            }
        });

        // 编辑表单 - 初始化表单验证器
        supplierEditionModal.find("form").validate({
            ignore: "",
            errorPlacement: function(error, element)
            {
                error.insertAfter(element);
            },
            submitHandler: function(form) {
            	var loading = window.top.window.getIndexBusyOverlay();
                var json = formJson(form);
                $.ajax({
                    method: "PUT",
                    contentType: "application/json; charset=UTF-8",
                    dataType: "json",
                    url: "/suppliers/" + supplierEditionModal.data("id") + ".action",
                    data: JSON.stringify({
                        name: json.supplierName,
                        enterpriseId: json.enterprise,
                        remark: json.supplierRemark
                    }),beforeSend:function(){
                        if(loading) {
                        	loading.settext("正在处理中，请稍后...");
                        }
                    }
                }).done(function() {
                	loading.remove();
                    supplierEditionModal.modal("hide");
                    dataTable.draw();
                    window.top.window.showScoMessage('ok', '编辑成功');
                }).fail(function(resp) {
                	loading.remove();
                    window.top.window.showModalAlert(resp.responseJSON.errorMessage);
                });
            }
        });

        // 初始化企业列表
        $.ajax({
            url: "/enterprise/getUserEnterpriseList.action",
            cache: true,
            dataType: "json"
        }).done(function(data) {
            var options = [];
            $(data.entName).each(function() {
                options.push($('<option></option>').attr("value", this.entId).text(this.entName));
            });
            $("select[name=enterprise]").append(options);
        }).fail(function(resp) {
            window.top.window.showModalAlert(resp.responseJSON.errorMessage);
        });

        // 共用函数定义
        function hideAdvanceSearchPanel() {
            $(SELECTORS.ADVANCE_SEARCH_PANEL).hide();
            $(SELECTORS.ADVANCE_SEARCH_ICON).children("i:eq(0)")
                .removeClass("fa-angle-double-up").addClass("fa-angle-double-down");
        }

        function formJson(form) {
            return $(form).serializeArray().reduce(function(a, b) {
                a[b.name] = b.value;
                return a;
            }, {});
        }

        $.prototype.field = function(field, value) {
            $(this).find("[name=" + field + "]").val(value);
            return $(this);
        }
    });

})();


